import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import {
  getColumns,
  patentTypes,
  statusOptions,
  departmentOptions,
  strategyTypes,
} from "./patentManagementColumns";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  DatePicker,
  Upload,
  message,
  Select,
  Switch,
  InputNumber,
  Row,
  Col,
  Tag,
  Tooltip,
} from "antd";
import {
  UploadOutlined,
  SearchOutlined,
  FilterOutlined,
  DownloadOutlined,
  PlusOutlined,
  FileExcelOutlined
} from "@ant-design/icons";
import * as XLSX from "xlsx";
import dayjs from "dayjs";
import {
  getPatentList,
  editPatent,
  deletePatent,
  importPatents,
  changePatentee,
  exportPatents,
  getPatentTemplate
} from "../actions/patentManagement";
import "../styles.css";

function PatentInfoTable(props) {
  const {
    dispatch,
    editPatentResult,
    deletePatentResult,
    importPatentsResult,
    changePatenteeResult,
    exportPatentsResult,
    patentTemplateResult
  } = props;
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [editingRecord, setEditingRecord] = useState(null);
  const [patentList, setPatentList] = useState([]);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [changeForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [changeModalVisible, setChangeModalVisible] = useState(false);
  const [uploadFile, setUploadFile] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchParams, setSearchParams] = useState({});

  // 获取专利列表
  const fetchPatentList = (params = {}) => {
    setLoading(true);
    const queryParams = {
      page: params.current || pagination.current,
      pageSize: params.pageSize || pagination.pageSize,
      keyword: params.keyword || "",
      patent_type: params.patent_type || "",
      certificate_issue_date: params.certificate_issue_date || "",
      ...params,
    };
    
    // 保存搜索参数，用于导出
    if (params.keyword !== undefined || params.patent_type !== undefined || params.certificate_issue_date !== undefined) {
      setSearchParams({
        keyword: params.keyword || "",
        patent_type: params.patent_type || "",
        certificate_issue_date: params.certificate_issue_date || "",
      });
    }
    
    dispatch(getPatentList(queryParams))
      .then((res) => {
        if (res && res.payload) {
          setPatentList(res.payload.data);
          setPagination((prev) => ({
            ...prev,
            current: res.payload.data.page || prev.current,
            pageSize: res.payload.data.pageSize || prev.pageSize,
            total: res.payload.data.total || 0,
          }));
        }
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchPatentList();
  }, []);

  // 列表数据更新时处理
  useEffect(() => {
    if (patentList) {
      setLoading(false);
      setPagination((prevPagination) => ({
        ...prevPagination,
        total: patentList.total,
        pageSize: patentList.pageSize || prevPagination.pageSize,
        current: patentList.page || prevPagination.current,
      }));
    }
  }, [patentList]);

  // 处理编辑/新增结果
  useEffect(() => {
    if (editPatentResult) {
      if (editPatentResult.error) {
        message.error(editPatentResult.message || "保存专利信息失败");
      } else {
        message.success("保存专利信息成功");
        fetchPatentList();
        setEditModalVisible(false);
      }
    }
  }, [editPatentResult]);

  // 处理删除结果
  useEffect(() => {
    if (deletePatentResult) {
      message.success("删除专利成功");
      fetchPatentList();
    }
  }, [deletePatentResult]);

  // 处理导入结果
  useEffect(() => {
    if (importPatentsResult) {
      message.success(
        `成功导入${importPatentsResult.successCount || 0}条专利数据`
      );
      fetchPatentList();
      setModalVisible(false);
      setUploadFile(null);
    }
  }, [importPatentsResult]);

  // 处理变更专利权人结果
  useEffect(() => {
    if (changePatenteeResult) {
      message.success("变更专利权人成功");
      fetchPatentList();
      setChangeModalVisible(false);
    }
  }, [changePatenteeResult]);

  // 处理导出结果
  useEffect(() => {
    if (exportPatentsResult) {
      if (exportPatentsResult.error) {
        message.error(exportPatentsResult.error || "导出专利数据失败");
      }
    }
  }, [exportPatentsResult]);

  // 处理获取模板结果
  useEffect(() => {
    if (patentTemplateResult) {
      if (patentTemplateResult.error) {
        message.error(patentTemplateResult.error || "获取专利导入模板失败");
      }
    }
  }, [patentTemplateResult]);

  // 表格变化处理（分页、排序等）
  const handleTableChange = (pagination, filters, sorter) => {
    setPagination((prev) => ({
      ...prev,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));

    fetchPatentList({
      current: pagination.current,
      pageSize: pagination.pageSize,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };

  const onEdit = (record) => {
    setEditingRecord(record);
    editForm.setFieldsValue({
      ...record,
      disclosure_collection_date: record.disclosure_collection_date
        ? dayjs(record.disclosure_collection_date)
        : null,
      acceptance_notice_date: record.acceptance_notice_date
        ? dayjs(record.acceptance_notice_date)
        : null,
      grant_notice_date: record.grant_notice_date
        ? dayjs(record.grant_notice_date)
        : null,
      certificate_issue_date: record.certificate_issue_date
        ? dayjs(record.certificate_issue_date)
        : null,
      invalidation_date: record.invalidation_date
        ? dayjs(record.invalidation_date)
        : null,
      agency_process_date: record.agency_process_date
        ? dayjs(record.agency_process_date)
        : null,
      cnipa_process_date: record.cnipa_process_date
        ? dayjs(record.cnipa_process_date)
        : null,
      change_procedure_date: record.change_procedure_date
        ? dayjs(record.change_procedure_date)
        : null,
    });
    setEditModalVisible(true);
  };

  const onDelete = (record) => {
    Modal.confirm({
      title: "确认删除？",
      content: `确定要删除专利「${record.patent_name}」吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        dispatch(deletePatent(record.id));
      },
    });
  };

  const onChangePatentee = (record) => {
    setEditingRecord(record);
    changeForm.setFieldsValue({
      original_patentee: record.patentee,
      changed_patentee: "",
      change_procedure_date: null,
    });
    setChangeModalVisible(true);
  };

  const handleChangePatenteeOk = () => {
    changeForm.validateFields().then((values) => {
      dispatch(
        changePatentee(editingRecord.id, {
          changed_patentee: values.changed_patentee,
          change_procedure_date:
            values.change_procedure_date?.format("YYYY-MM-DD"),
        })
      );
    });
  };

  const handleEditOk = () => {
    editForm.validateFields().then((values) => {
      const formattedValues = {
        ...values,
        disclosure_collection_date:
          values.disclosure_collection_date?.format("YYYY-MM-DD"),
        acceptance_notice_date:
          values.acceptance_notice_date?.format("YYYY-MM-DD"),
        grant_notice_date: values.grant_notice_date?.format("YYYY-MM-DD"),
        certificate_issue_date:
          values.certificate_issue_date?.format("YYYY-MM-DD"),
        invalidation_date: values.invalidation_date?.format("YYYY-MM-DD"),
        agency_process_date: values.agency_process_date?.format("YYYY-MM-DD"),
        cnipa_process_date: values.cnipa_process_date?.format("YYYY-MM-DD"),
        change_procedure_date:
          values.change_procedure_date?.format("YYYY-MM-DD"),
      };

      const id = editingRecord ? editingRecord.id : "new";
      dispatch(editPatent(id, formattedValues))
        .catch(err => {
          message.error("保存专利信息失败: " + (err.message || "未知错误"));
        });
    })
    .catch(err => {
      message.error("表单验证失败，请检查必填字段");
    });
  };

  // 处理文件上传
  const handleFileUpload = (info) => {
    setUploadFile(info.file);
  };

  // 执行导入操作
  const handleImport = () => {
    if (!uploadFile) {
      message.error("请先选择要导入的Excel文件");
      return;
    }

    const formData = new FormData();
    formData.append("file", uploadFile);
    dispatch(importPatents(formData));
  };

  // 导出专利数据
  const handleExport = () => {
    // 构建查询参数
    const params = {
      ...searchParams
    };
    
    // 如果有选中行，则只导出选中行
    if (selectedRowKeys.length > 0) {
      params.ids = selectedRowKeys.join(',');
    }
    
    // 使用浏览器直接下载文件，而不是通过 Redux
    const exportUrl = `${window.location.origin}/_api/patentManagement/export?${new URLSearchParams(params).toString()}`;
    
    console.log("导出专利URL:", exportUrl); // 添加日志以便调试
    
    // 创建一个临时链接并点击，触发下载
    const link = document.createElement("a");
    link.href = exportUrl;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 下载专利导入模板
  const handleDownloadTemplate = () => {
    // 直接下载模板文件
    const templateUrl = `${window.location.origin}/api/patentManagement/template`;
    
    console.log("下载模板URL:", templateUrl); // 添加日志以便调试
    
    // 创建一个临时链接并点击，触发下载
    const link = document.createElement("a");
    link.href = templateUrl;
    link.target = "_blank";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedKeys) => {
      setSelectedRowKeys(selectedKeys);
    }
  };

  // 获取表格列配置
  const columns = getColumns({
    onEdit,
    onDelete,
    onChangePatentee,
  });

  return (
    <div>
      <div
        className="search-area"
        style={{
          marginBottom: 16,
          padding: "16px",
          backgroundColor: "#f0f2f5",
          borderRadius: "4px",
        }}
      >
        <Form
          form={form}
          layout="inline"
          onFinish={(values) => {
            const params = {
              ...values,
              current: 1,
              certificate_issue_date: values.certificate_issue_date
                ? values.certificate_issue_date.format("YYYY-MM-DD")
                : null,
            };
            fetchPatentList(params);
          }}
        >
          <Form.Item label="关键字:" name="keyword">
            <Input
              placeholder="专利名称、第一发明人、案号"
              style={{ width: 240 }}
            />
          </Form.Item>
          <Form.Item label="专利类型:" name="patent_type">
            <Select
              placeholder="请选择"
              style={{ width: 150 }}
              allowClear
              options={patentTypes.map((type) => ({
                label: type,
                value: type,
              }))}
            />
          </Form.Item>
          <Form.Item label="下证发文日期:" name="certificate_issue_date">
            <DatePicker style={{ width: 150 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={() => {
                form.resetFields();
                fetchPatentList({ current: 1 });
                setSearchParams({});
              }}
            >
              重置
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={() => {
                setEditingRecord(null);
                editForm.resetFields();
                setEditModalVisible(true);
              }}
              icon={<PlusOutlined />}
              style={{ marginRight: 8 }}
            >
              新增专利
            </Button>
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              onClick={() => setModalVisible(true)}
              icon={<UploadOutlined />}
              style={{ marginRight: 8 }}
            >
              导入专利
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              onClick={handleExport}
              icon={<DownloadOutlined />}
              style={{ marginRight: 8 }}
            >
              导出专利
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              onClick={handleDownloadTemplate}
              icon={<FileExcelOutlined />}
            >
              下载模板
            </Button>
          </Form.Item>
        </Form>
      </div>

      <div className="patent-table-container">
        <Table
          columns={columns}
          dataSource={patentList?.data || []}
          rowKey="id"
          rowSelection={rowSelection}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            pageSizeOptions: ["10", "20", "50", "100"],
          }}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: "max-content", y: 500 }}
          size="small"
          rowClassName={() => "custom-table-row"}
        />
      </div>

      {/* 导入专利弹窗 */}
      <Modal
        title="导入专利数据"
        open={modalVisible}
        onOk={handleImport}
        onCancel={() => {
          setModalVisible(false);
          setUploadFile(null);
        }}
        okText="导入"
        cancelText="取消"
      >
        <Upload
          beforeUpload={(file) => {
            // 只接受Excel文件
            const isExcel =
              file.type ===
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
              file.type === "application/vnd.ms-excel";
            if (!isExcel) {
              message.error("只能上传Excel文件!");
              return Upload.LIST_IGNORE;
            }
            setUploadFile(file);
            return false; // 阻止自动上传
          }}
          fileList={uploadFile ? [uploadFile] : []}
          onRemove={() => setUploadFile(null)}
          maxCount={1}
        >
          <Button icon={<UploadOutlined />}>选择Excel文件</Button>
        </Upload>
        <div style={{ marginTop: 16 }}>
          <p>注意：导入前请确保数据格式正确，专利名称和申请号为必填项</p>
          <p>如需模板，请点击"下载模板"按钮</p>
        </div>
      </Modal>

      {/* 变更专利权人弹窗 */}
      <Modal
        title="变更专利权人"
        open={changeModalVisible}
        onOk={handleChangePatenteeOk}
        onCancel={() => setChangeModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Form form={changeForm} layout="vertical">
          <Form.Item label="原专利权人" name="original_patentee">
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="变更后专利权人"
            name="changed_patentee"
            rules={[{ required: true, message: "请输入变更后专利权人" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="变更手续合格日期"
            name="change_procedure_date"
            rules={[{ required: true, message: "请选择日期" }]}
          >
            <DatePicker style={{ width: "100%" }} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑/新增专利弹窗 */}
      <Modal
        title={editingRecord ? "编辑专利信息" : "新增专利信息"}
        open={editModalVisible}
        onOk={handleEditOk}
        onCancel={() => setEditModalVisible(false)}
        width={1000}
        bodyStyle={{ maxHeight: "600px", overflow: "auto" }}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ flex: "160px" }}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Row gutter={16}>
            {[
              ["case_number", "我司案号", <Input />, true],
              ["patent_name", "专利名称", <Input />, true],
              ["application_number", "专利申请号", <Input />, true],
              [
                "patent_type",
                "专利类型",
                <Select
                  options={patentTypes.map((v) => ({ label: v, value: v }))}
                />,
                true
              ],
              [
                "disclosure_collection_date",
                "技术交底书收集时间",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "acceptance_notice_date",
                "受理发文",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "grant_notice_date",
                "授权发文",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "certificate_issue_date",
                "下证发文",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "invalidation_date",
                "无效日期",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "agency_process_date",
                "代理机构处理时间",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "cnipa_process_date",
                "国知局处理时间",
                <DatePicker style={{ width: "100%" }} />,
                true
              ],
              [
                "patent_status",
                "专利状态",
                <Select
                  options={statusOptions.map((v) => ({ label: v, value: v }))}
                />,
                true
              ],
              [
                "fast_track",
                "是否走快审通道",
                <Switch checkedChildren="是" unCheckedChildren="否" />,
                true
              ],
              ["patentee", "专利权人", <Input />, true],
              ["changed_patentee", "变更后专利权人", <Input />, false],
              [
                "change_procedure_date",
                "变更手续合格日期",
                <DatePicker style={{ width: "100%" }} />,
                false
              ],
              ["inventors", "发明人", <Input />, true],
              ["first_inventor", "第一发明人", <Input />, true],
              [
                "department",
                "来源部门",
                <Select
                  options={departmentOptions.map((v) => ({
                    label: v,
                    value: v,
                  }))}
                />,
                true
              ],
              ["related_product", "关联产品", <Input />, true],
              ["related_project", "关联立项/课题", <Input />, true],
              [
                "strategy_type",
                "防御型/攻击型",
                <Select
                  options={strategyTypes.map((v) => ({ label: v, value: v }))}
                />,
                true
              ],
              [
                "is_core",
                "是否为核心",
                <Switch checkedChildren="是" unCheckedChildren="否" />,
                true
              ],
              [
                "core_score",
                "核心分数",
                <InputNumber min={0} max={100} style={{ width: "100%" }} />,
                true
              ],
              ["original_disclosure_name", "原始交底书名称", <Input />, true],
              ["agency", "代理机构", <Input />, true],
              ["manager", "负责人", <Input />, true],
              ["agency_case_number", "代理案号", <Input />, true],
              ["special_notes", "特殊事项备注", <Input.TextArea rows={2} />, false],
              [
                "related_development_project",
                "（发展部）关联课题/项目",
                <Input />,
                false
              ],
            ].map(([name, label, component, required]) => (
              <Col span={12} key={name}>
                <Form.Item
                  name={name}
                  label={label}
                  valuePropName={
                    component.type === Switch ? "checked" : "value"
                  }
                  rules={[
                    { required: required, message: `请输入${label}` }
                  ]}
                >
                  {component}
                </Form.Item>
              </Col>
            ))}
          </Row>
        </Form>
      </Modal>
    </div>
  );
}

function mapStateToProps(state) {
  const {
    patentList,
    editPatentResult,
    deletePatentResult,
    importPatentsResult,
    changePatenteeResult,
    exportPatentsResult,
    patentTemplateResult
  } = state.patentManagement || {};
  return {
    patentList,
    editPatentResult,
    deletePatentResult,
    importPatentsResult,
    changePatenteeResult,
    exportPatentsResult,
    patentTemplateResult
  };
}

export default connect(mapStateToProps)(PatentInfoTable);
